<?php
error_reporting(0);
require 'lib.php';

$server = "172.21.147.31";
$connectionInfo = array( "Database"=>"ss2g6", "UID"=>"ss2g6", "PWD"=>"group6", 'ReturnDatesAsStrings'=> true );
$conn = sqlsrv_connect( $server, $connectionInfo );

if ($conn == false){
	 die( print_r( sqlsrv_errors(), true));
}
$params = array();
$options =  array( "Scrollable" => SQLSRV_CURSOR_KEYSET );

/* Update GET */
if(isset($_GET['update'])){
    $updatePatientId = $_GET['patientId'];
    $sql = "SELECT * FROM Patient WHERE patientId = $updatePatientId";
    $result = sqlsrv_query($conn, $sql, $params, $options);
    $row = sqlsrv_fetch_array( $result, SQLSRV_FETCH_ASSOC);

	$updateAge = $row['age'];
    $updateName = $row['name'];
    $updateAddress = $row['address'];
    $updateDoctorId = $row['doctorId'];
}


/* Update POST */
if (isset($_POST['Update'])){
    $updatePatientIdOld = $_POST['updatePatientIdOld'];
	$updateAge = $_POST['age'];
    $updateName = $_POST['name'];
    $updateAddress = $_POST['address'];
    $updateDoctorId = $_POST['doctorId'];
    
    if( $updateName == "" || $updateAddress == "" || $updateDoctorId == ""){
		$validation_error = true;
	}
	else {
		$validation_error = false;
	}
	
	if(is_numeric($updateAge) || is_numeric($updateDoctorId)){
		$numeric = true;
	}
	else {
		$numeric = false;
    }

    if ($validation_error || !$numeric){
        $update_error = true;
    }
	
    if (!isset($update_error)){
        $sql = "UPDATE Patient SET age=$updateAge, name='$updateName', address = '$updateAddress', doctorId =$updateDoctorId WHERE patientId = $updatePatientIdOld";
        $result = sqlsrv_query($conn, $sql, $params, $options);
        $result = sqlsrv_query( $conn, $sql, $params);
	if ($result == false){
		 if(($errors = sqlsrv_errors()) != null){
            $error_msg = "";
            foreach($errors as $error){
                $error_msg = $error_msg . " " . cut_string_using_last(']', $error['message'], 'right', false);
            }
        }
	}
	else{
        $rowsAffected = sqlsrv_rows_affected ($result);
	
	    if ($rowsAffected == false){
		     $error = true;     
	    }
	    else{
		    $error = false;
	    }
   }
	    $confirm = "The patient information is updated.";
    }
}
if(isset($_POST['Insert'])) {
    $age = $_POST['age'];
    $name = $_POST['name'];
    $address = $_POST['address'];
    $doctorId = $_POST['doctorId'];
	
	/* check empty fields */
	if($age == "" || $name == "" || $address == ""){
		$validation_error = true;
	}
	else {
		$validation_error = false;
	}
	
	/*check whether age is a numeric number */
	if(is_numeric($age)){
		$numeric = true;
	}
	else {
		$numeric = false;
	} 
	
    $sql = "INSERT INTO Patient VALUES ('$age', '$name', '$address', '$doctorId')";
	
	 if($validation_error == false && $numeric == true){
    $params = array();
    $result = sqlsrv_query( $conn, $sql, $params);
	if ($result == false){
		 if(($errors = sqlsrv_errors()) != null){
            $error_msg = "";
            foreach($errors as $error){
                $error_msg = $error_msg . " " . cut_string_using_last(']', $error['message'], 'right', false);
            }
        }
	}
	else{
        $rowsAffected = sqlsrv_rows_affected ($result);
	
	    if ($rowsAffected == false){
		     $error = true;     
	    }
	    else{
		    $error = false;
	    }
   }
	
    $confirm = "The Patient information is inserted.";
	}
	else {
		$confirm = "";
	}
	
}

if(isset($_GET['delete'])){
	$patientId = $_GET['patientId'];
	$sql = "DELETE FROM Patient WHERE patientId = '". $patientId . "'";
	$params = array();
    $options =  array( "Scrollable" => SQLSRV_CURSOR_KEYSET );
    $result = sqlsrv_query( $conn, $sql, $params);
	if ($result == false){
        if(($errors = sqlsrv_errors()) != null){
            $error_msg = "";
            foreach($errors as $error){
                $error_msg = $error_msg . " " . cut_string_using_last(']', $error['message'], 'right', false);
            }
        }
	}
	else{
        $rowsAffected = sqlsrv_rows_affected ($result);	
	    if ($rowsAffected == false){	    	
		     $error = true;     
	    }
	    else{	    	
		    $error = false;
	    }
   }
	

}

if (isset($_POST['submit'])){
    $sql1 = $_POST['query'];
}
else
{
    $sql = "SELECT * FROM Patient";
}

$params = array();
$options =  array( "Scrollable" => SQLSRV_CURSOR_KEYSET );
$stmt = sqlsrv_query( $conn, $sql , $params, $options );
?>


<? include 'html_head.php' ?>
    <? include 'header.php' ?>

    <div class="container-fluid">
      <div class="row-fluid">
        <div class="span2">
                <? include 'sidebar.php' ?>
        </div><!--/span-->
        <div class="span9">
		<h2>Patient</h2>	
	    <hr>
		<?
        /* print trigger errors if any first, then a general error message*/
		if(isset($_GET['delete'])){
            if (isset($error_msg)){ ?>
				<div class="alert alert-error">
					<? echo $error_msg; ?>
				</div>
            <?
            }
            elseif ($error){ ?>
				<div class="alert alert-error">
                    <? echo "Unable to delete."; ?>
				</div>
				
			<? 
			} 
			else { ?>
				<div class="alert alert-success">
				<? echo "Data deleted successfully."?>
				</div>
				
			<?
			} 
		}?>
		
		<?
			if(isset($_POST['Update'])){
				$msg = "";
				if($numeric == false){ 
					$msg = "Age text field must be an integer value <br />";
				}
				if($validation_error){
					$msg = $msg . "No text fields can be empty";
				}
				if(isset($error_insert) && $error_insert){
					$msg = "Data cannot be inserted, foreign key constraints or triggers violated <br />";
				}
				if (isset($error_msg)){ ?>
                    <div class="alert alert-error">
                        <? echo $error_msg; ?>
                    </div>
                <?
                }
				else if ($msg <> ""){ ?>
					<div class="alert alert-error">
						<? echo $msg; ?>
					</div>
				<?
				}else { ?>
					<div class="alert alert-success">
					<? echo $confirm;?>
					</div>
					
				<?
				} 
			}?>
			
        <?
			if(isset($_POST['Insert'])){
				$msg = "";
                
				if($numeric == false){ 
					$msg = "Age text field must be an integer value <br />";
				}
				if($validation_error){
					$msg = $msg . "No text fields can be empty";
				}
				if(isset($error_insert) && $error_insert){
					$msg = "Data cannot be inserted, foreign key constraints or triggers violated <br />";
				}
				
                if (isset($error_msg)){ ?>
                    <div class="alert alert-error">
                        <? echo $error_msg; ?>
                    </div>
                <?
                }
				else if ($msg <> ""){ ?>
					<div class="alert alert-error">
						<? echo $msg; ?>
					</div>
				<?
				}else { ?>
					<div class="alert alert-success">
					<? echo $confirm;?>
					</div>
					
				<?
				} 
			}?>
		<?
        
		if(sqlsrv_has_rows($stmt))
		{		
			$row_count = sqlsrv_num_rows($stmt);
            $colnames = sqlsrv_field_metadata($stmt)
		?>
		
		<table class="table table-striped table table-condensed">
		
		<thead>
			<tr>
                <?
                    echo "<th>Patient ID</th>";
					echo "<th>Age</th>";
					echo "<th>Name</th>";
                    echo "<th>Address</th>";
					echo "<th>Doctor ID</th>";
                ?>
			</tr>	
			</thead>
		<tbody>
		<?
			while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC)){
		?>
			<tr>
				<?
					echo "<td>" . $row['patientId'] . "</td>";
					echo "<td>" . $row['age'] . "</td>";
					echo "<td><a href='patientrecord.php?patientId=" . $row['patientId'] . "'>" . $row['name'] . "</a></td>";
					echo "<td>" . $row['address'] . "</td>";
					echo "<td>" . $row['doctorId'] . "</td>";
					echo "<td>";
					
					$patientId = urlencode($row['patientId']);
					echo "<td><a href='patients.php?delete=true&patientId=" . $patientId . "'>Delete</a></td>";
					echo "<td><a href='patients.php?update=true&patientId=" . $patientId . "#updates'>Update</a></td>";
				?>
			</tr>
		  
		<?
			}
		?>
		</tbody>
		</table>
		<?
		}
		else{
			echo "<h2>No records.</h2>";
		}
		?>
          <div class="row-fluid">
            <div class="span12">
			<!-- Update, appears only if update or update_error is set -->
            <? if (isset($_GET['update']) || isset($update_error)){ ?>
            <div>
                <a name="updates"></a><h3>Update Patient information:</h3> 
                <form method="post" action="patients.php" class="well form-horizontal">
                    <div class="control-group">
                    	<label class="control-label">Patient ID</label>
                    	<div class="controls"><input type="text" name="updatePatientIdOld" value="<? echo $updatePatientId ?>" readonly /></div>
                    </div>
                    <div class="control-group">
                        <label class="control-label">Age</label>
                        <div class="controls">
                            <input type="text" name="age" id="age" value="<? echo $updateAge ?>" /> 
                        </div>
                    </div>
                    <div class="control-group">
                        <label class="control-label">Name</label>
                        <div class="controls">
                            <input type="text" name="name" id="name" value="<? echo $updateName ?>"/>
                        </div> 
                    </div>
                    <div class="control-group">
                        <label class="control-label">Address</label>
                        <div class="controls">
                            <input type="text" name="address" id="address" value="<? echo $updateAddress ?>"/>
                        </div>
                    </div>
					<div class="control-group">
                        <label class="control-label">Doctor ID</label>
                        <div class="controls">
                        	<? 
								$sql2 = "SELECT doctorId FROM Doctor order by doctorId ASC";
								$result = sqlsrv_query($conn,$sql2);
								echo "<select name = 'doctorId'>";
								while ($data=sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)){
									echo "<option ";
                                    if ($data['doctorId'] == $updateDoctorId){
                                        echo "selected=selected";
                                    }
                                    echo ">";
									echo $data['doctorId']; 
									echo "</option>";
								}
								echo "</select>";
							?>    
							<span class="help-inline"><a href="doctors.php" target="_blank">Create new Doctor</a></span>                        
                        </div>
                    </div>
                    <div class="form-actions">
                        <input type="submit" name="Update" value="Update"  class="btn btn-primary"/>
                    </div> 
                    </form>

            </div>
            <? } ?>
            <h3>Create a new Patient information:</h3> 
                    <form method="post" action="patients.php" class="well form-horizontal">
                    <div class="control-group">
                        <label class="control-label">Name</label>
                        <div class="controls">
                            <input type="text" name="name" id="name" placeholder="eg. Linda Chong" />
                        </div>
                    </div>
                    <div class="control-group">
                        <label class="control-label">Age</label>
                        <div class="controls">
                            <input type="text" name="age" id="age" placeholder="eg. 21"/>
                        </div> 
                    </div>
                    <div class="control-group">
                        <label class="control-label">Address</label>
                        <div class="controls">
                            <input type="text" name="address" id="address" placeholder="eg. Blk 436 Fajar Road #12-386 Singapore 670436" />
                        </div>
                    </div>
                    <div class="control-group">
                        <label class="control-label">Doctor ID</label>
                        <div class="controls">
                            <? 
								$sql2 = "SELECT doctorId FROM Doctor order by doctorId ASC";
								$result = sqlsrv_query($conn,$sql2);
								echo "<select name = 'doctorId'>";
								while ($data=sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)){
									echo "<option>";
									echo $data['doctorId']; 
									echo "</option>";
								}
								echo "</select>";
							?>
                            <!--<input type="text" name="doctorId" id="doctorId" placeholder="Id of Primary physician" />-->
                            <span class="help-inline"><a href="doctors.php" target="_blank">Create new Doctor</a></span>
                        </div>
                    </div>
                    <div class="form-actions">
                        <input type="submit" name="Insert" value="Insert"  class="btn btn-primary"/>
                    </div> 
                    </form>
              <h3>Enter your query:</h3>
                    <form method="post" action="custom.php" class="well form-inline">
                    <div class="control-group">
                        <div class="controls">
                            <textarea name="query" class="span10" id="textarea" rows="5" placeholder = 'SQL query'></textarea>
                        </div>
                    </div>
                    <p>
                    <p><input type="submit" name="submit" class="btn btn-primary" href="#" /></p>
                    </form>
                    
            </div><!--/span-->
          </div><!--/row-->
        </div><!--/span-->
      </div><!--/row-->

      <hr>

      <footer>
        <p>&copy; SS2 GROUP 6 </p>
      </footer>

    </div><!--/.fluid-container-->
  </body>
</html>
